package com.sec.android.app.myfiles.module.local.recent;

import android.content.Context;
import android.database.Cursor;
import android.database.CursorIndexOutOfBoundsException;
import android.view.View;
import android.view.ViewStub;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.decorator.dlpinfo.DlpAdapterDecorator;
import com.sec.android.app.myfiles.decorator.privateinfo.PrivateAdapterDecorator;
import com.sec.android.app.myfiles.feature.DlpMgr;
import com.sec.android.app.myfiles.fragment.AbsMyFilesFragment;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsFileListAdapterImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.abstraction.FileRecord.StorageType;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.provider.DbTableInfo;
import com.sec.android.app.myfiles.provider.DbTableInfo.COLUMN_ID;
import com.sec.android.app.myfiles.thumbnail.ThumbnailImageView;
import com.sec.android.app.myfiles.util.FileUtils;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.UiUtils;
import com.sec.android.app.myfiles.widget.listview.AbsListViewImp;
import com.sec.android.app.myfiles.widget.listview.FileListViewHolder;
import com.sec.android.app.myfiles.widget.listview.ListViewHolder;

import java.util.Locale;


public class RecentAdapterImp extends AbsFileListAdapterImp {
    private int mMaxItemCount = -1;
    private int mPreTotCount = -1;

    public RecentAdapterImp(Context context, NavigationInfo navigationInfo, AbsListViewImp listView, Cursor c, int flags) {
        super(context, navigationInfo, listView, c, flags);
        initRecentAdapterImp();
    }

    public RecentAdapterImp(Context context, NavigationInfo navigationInfo, int layoutId, Cursor c, int flags) {
        super(context, navigationInfo, layoutId, c, flags);
        initRecentAdapterImp();
    }

    private void initRecentAdapterImp() {
        if (mTableInfo == null) {
            mTableInfo = RecentDbTableInfo.getInstance();
        }
    }

    @Override
    protected ListViewHolder _createViewHolder(View v) {
        ListViewHolder vh = super._createViewHolder(v);
        vh.addView(FileListViewHolder.DLP_ICON_STUB, v.findViewById(R.id.dlp_icon_stub));
        vh.addView(FileListViewHolder.PRIVATE_ICON_STUB, v.findViewById(R.id.private_icon_stub));

        return vh;
    }

    private boolean isHomeRecentRecord() {
        boolean bRet = false;
        if (mCurRecord != null) {
            bRet = (mCurRecord.getStorageType() == StorageType.Home);
        }
        return bRet;
    }

    public void updateRecentItemMaxCount(int maxItemCount) {
        if (isHomeRecentRecord()) {
            mMaxItemCount = maxItemCount;
        }
    }

    public int getRecentItemMaxCount() {
        return mMaxItemCount;
    }

    @Override
    public int getCount() {
        int count = super.getCount();
        if (mMaxItemCount > 0 && mMaxItemCount < count) {
            return mMaxItemCount;
        } else {
            return count;
        }
    }

    public int getTotalCount() {
        int ret = 0;
        Cursor cursor = getCursor();
        if (cursor != null) {
            ret = cursor.getCount();
        }
        return ret;
    }

    @Override
    public String getSelection() {
        boolean showHidden = PreferenceUtils.getShowHiddenFiles(mContext);
        String where = null;
        if (!showHidden) {
            StringBuilder sb = new StringBuilder();
            String path = mTableInfo.getColumnName(COLUMN_ID.PATH);
            String name = mTableInfo.getColumnName(COLUMN_ID.NAME);

            sb.append(" ((LOWER(").append(path).append(") NOT LIKE '%/.%')  AND NOT(").append(name).append(" LIKE '.%'))");
            // where = mTableInfo.getColumnName(COLUMN_ID.PATH) + " NOT LIKE '%/.%'";
            if (sb.length() > 0) {
                where = sb.toString();
            }
        }
        return where;
    }

    @Override
    public String[] getSelectionArgs() {
        return null;
    }

    @Override
    public String getOrderBy() {
        return mTableInfo.getColumnName(COLUMN_ID.RECENT_DATE) + " DESC";
    }

    @Override
    protected FileRecord _getFileRecord(Cursor cursor) {
        FileRecord ret = null;
        try {
            ret = getRecentFileRecord(cursor, mTableInfo);
        } catch (CursorIndexOutOfBoundsException e) {
            Log.e(this, "CursorIndexOutOfBoundsException: " + e.toString());
        }
        return ret;
    }

    public static FileRecord getRecentFileRecord(Cursor cursor, DbTableInfo tableInfo) {
        FileRecord ret = null;

        final int downloadIdIndex = tableInfo.getIndex(COLUMN_ID.DOWNLOAD_ID);
        final int pathIndex = tableInfo.getIndex(COLUMN_ID.PATH);
        final int nameIndex = tableInfo.getIndex(COLUMN_ID.NAME);
        final int sizeIndex = tableInfo.getIndex(COLUMN_ID.SIZE);
        final int dateIndex = tableInfo.getIndex(COLUMN_ID.DATE);
        final int typeIndex = tableInfo.getIndex(COLUMN_ID.FILE_TYPE);
        final int sourceIndex = tableInfo.getIndex(COLUMN_ID.SOURCE);
        final int descIndex = tableInfo.getIndex(COLUMN_ID.DESCRIPTION);
        final int statusIndex = tableInfo.getIndex(COLUMN_ID.STATUS);
        final int downloadByIndex = tableInfo.getIndex(COLUMN_ID.DOWNLOAD_BY);
        final int isGear360ContentsIndex = tableInfo.getIndex(COLUMN_ID.IS_360_CONTENTS);
        final int lastAccessedTimeIndex = tableInfo.getIndex(COLUMN_ID.RECENT_DATE);

        if (cursor != null && !cursor.isClosed()) {
            int downloadId = cursor.getInt(downloadIdIndex);
            String path = cursor.getString(pathIndex);
            String name = cursor.getString(nameIndex);
            long size = cursor.getLong(sizeIndex);
            long date = cursor.getLong(dateIndex);
            int fileType = cursor.getInt(typeIndex);
            String source = cursor.getString(sourceIndex);
            String description = cursor.getString(descIndex);
            int status = cursor.getInt(statusIndex);
            int download = cursor.getInt(downloadByIndex);
            int isGear360Contents = cursor.getInt(isGear360ContentsIndex);
            long lastAccessedTime = cursor.getLong(lastAccessedTimeIndex);

            ret = new RecentFileRecord(downloadId, path, name, size, date, fileType, source, description, status, download, lastAccessedTime);
            ret.setGear360Contents(isGear360Contents == 1);
        }
        return ret;
    }

    @Override
    public String getFilePath(Cursor cursor) {
        return getFilePath(cursor, mTableInfo.getIndex(COLUMN_ID.PATH));
    }

    @Override
    public StorageType getStorageType() {
        return StorageType.Recent;
    }

    private boolean isLastItem(int position) {
        return getTotalCount() > mMaxItemCount && position == (mMaxItemCount - 1);
    }

    private void bindHomeRecentView(Context context, ListViewHolder vh, View v, FileRecord record, int position) {
        boolean isLastItem = isLastItem(position);
        ThumbnailImageView thumbnailView = (ThumbnailImageView) vh.getView(FileListViewHolder.THUMBNAIL);
        View name = vh.getView(FileListViewHolder.NAME);
        View nameBgView = v.findViewById(R.id.file_detail_info);
        if (thumbnailView != null) {
            thumbnailView.setIsRecentLastItem(isLastItem);
        }
        if (isLastItem) {
            ensureMoreView(v);
            if (name != null) {
                name.setVisibility(View.INVISIBLE);
            }
            if (nameBgView != null) {
                nameBgView.setVisibility(View.GONE);
            }
            v.setContentDescription(UiUtils.getHomeDescription(mContext, R.string.subtitle_recent, R.string.button));
        } else {
            View more = v.findViewById(R.id.more);
            if (more != null) {
                more.setVisibility(View.GONE);
            }
            if (name != null) {
                name.setVisibility(View.VISIBLE);
            }
            if (nameBgView != null) {
                nameBgView.setVisibility(View.VISIBLE);
            }
        }
        _bindThumbnailView(context, vh, v, record);
        _bindDefaultInfoView(context, vh, record);
    }

    @Override
    protected void _bindView(Context context, ListViewHolder vh, View v, FileRecord record, int position) {
        if (isHomeRecentRecord()) {
            bindHomeRecentView(context, vh, v, record, position);
        } else {
            super._bindView(context, vh, v, record, position);
        }
        _bindPrivateIcon(vh, v, record);
        _bindDLPIcon(context, vh, v, record);
    }

    private void _bindPrivateIcon(ListViewHolder vh, View v, final FileRecord record) {
        boolean isPrivate = FileUtils.isPrivateFolder(record.getPath());
        PrivateAdapterDecorator.showPrivateIcon(vh, v, isPrivate);
    }

    private void _bindDLPIcon(Context context, ListViewHolder vh, View v, final FileRecord record) {
        boolean isDLP = DlpMgr.getInstance(context).isDlpFile(record);
        DlpAdapterDecorator.showDLPIcon(vh, v, isDLP);
    }

    private void ensureMoreView(View v) {
        ViewStub moreStub = (ViewStub) v.findViewById(R.id.more_stub);
        View more;
        if (moreStub == null) {
            more = v.findViewById(R.id.more);
        } else {
            more = moreStub.inflate();
        }
        if (more != null) {
            more.setVisibility(View.VISIBLE);
            TextView moreText = (TextView) more.findViewById(R.id.text);
            if (moreText != null) {
                String moreInfo = String.format(Locale.getDefault(), "%d", ((getTotalCount() - mMaxItemCount) + 1)) + "+";
                moreText.setText(moreInfo);
                setEnableMoreText(moreText);
            }
        }
        if (mCheckMode) {
            View checkbox = v.findViewById(R.id.checkbox);
            if (checkbox != null) {
                checkbox.setVisibility(View.GONE);
            }
        }
    }

    private void setEnableMoreText(View more) {
        if (more != null) {
            more.setAlpha(!mCheckMode ? 1.0f : 0.4f);
        }
    }

    @Override
    protected boolean isDetailList(View v) {
        return false;
    }

    @Override
    public boolean areAllItemsEnabled() {
        return false;
    }

    @Override
    protected void doFragmentLoadFinished(AbsMyFilesFragment fragment, Cursor data) {
        int curTotCnt = data.getCount();
        if (mPreTotCount != curTotCnt) {
            fragment.onLoadFinished();
        }

        mPreTotCount = curTotCnt;
    }

    @Override
    public boolean _isEnabled(int position) {
        if ((mCheckMode && isLastItem(position)) || !isCheckable(position)) {
            return false;
        } else {
            return true;
        }
    }

    @Override
    public int getEmptySubTextId() {
        return R.string.no_recent_files;
    }
}
